#!/bin/bash
#
#	Postgresql plugin for the Eloy backup system.
#
#	Copyright (c) 2007-2008 Maximilian Antoni. All rights reserved.
#
#	This software is licensed as described in the file LICENSE.txt, which you
#	should have received as part of this distribution. The terms are also
#	available at http://svn.evaserver.com/eloy/trunk/LICENSE.txt.
#

#
#	Backup created with this script can be restored like this:
#
#	psql -c 'drop schema public cascade' -d DB_NAME -U postgres
#	psql -c 'create schema public' -d DB_NAME -U postgres
#	psql -f db-backup-DB_NAME-utf8.sql -d DB_NAME -U postgres
#
DB_NAMES="eloy"
for DB_NAME in $DB_NAMES
do
	out "Creating backup for \"$DB_NAME\"."
	DB_BACKUP_FILE="db-backup-$DB_NAME-utf8.sql"
	DB_BACKUP_PATH="/home/postgres/$DB_BACKUP_FILE"
	if [ -f "$DB_BACKUP_PATH.new" ]; then
		su - postgres -c "rm $DB_BACKUP_PATH.new"
	fi
	su - postgres -c "pg_dump -U postgres -f $DB_BACKUP_FILE.new --encoding utf-8 $DB_NAME"
	if [ $? -ne 0 ]; then
		out "pg_dump for \"$DB_NAME\" FAILED"
		continue
	fi
	if [ -f "$DB_BACKUP_PATH" ]; then
		cmp --silent "$DB_BACKUP_PATH" "$DB_BACKUP_PATH.new"
		if [ $? -eq 0 ]; then
			su - postgres -c "rm $DB_BACKUP_PATH.new"
			continue
		fi
		su - postgres -c "rm $DB_BACKUP_PATH"
	fi
	su - postgres -c "mv $DB_BACKUP_PATH.new $DB_BACKUP_PATH"
done
